package com.live.shop.home.setting;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.live.shop.BaseActivity;
import com.live.shop.R;
import com.live.shop.model.UserModel;
import com.live.shop.sql.UserDatabase;
import com.live.shop.tool.GetUtil;
import com.live.shop.tool.OkHttpUtils;
import com.live.shop.tool.StatusBarUtils;
import com.live.shop.tool.UpdateChecker;
import com.live.shop.view.ToastBottomUtils;
import com.live.shop.view.ToastUtils;
import com.live.shop.view.XCRoundImageView;

import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Response;

public class SettingActivity extends BaseActivity {
    ImageButton setting_back;
    XCRoundImageView setting_headurl;
    RelativeLayout setting_nickname;
    TextView setting_nickname_value;
    TextView setting_pass;
    TextView setting_permission;
    TextView setting_update;
    TextView setting_aboutus;
    TextView setting_proxy;
    TextView setting_opinion;
    TextView setting_aliyun;

    ImageView setting_comment_keep;
    EditText setting_prologue_interval;
    EditText setting_pc;
    ImageView setting_prologue_break;
    ImageView setting_prologue_restart;
    ImageView setting_prologue_playtype;
    ImageView setting_keyword_keeptype;
    UserDatabase userDb;
    UserModel userModel;

    String newNickname = "";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        StatusBarUtils.setDarkStatusWhite(this,R.color.white);

        setting_back = findViewById(R.id.setting_back);
        setting_headurl = findViewById(R.id.setting_headurl);
        setting_nickname = findViewById(R.id.setting_nickname);
        setting_nickname_value = findViewById(R.id.setting_nickname_value);
        setting_pass = findViewById(R.id.setting_pass);
        setting_permission = findViewById(R.id.setting_permission);
        setting_update = findViewById(R.id.setting_update);
        setting_aboutus = findViewById(R.id.setting_aboutus);
        setting_proxy = findViewById(R.id.setting_proxy);
        setting_opinion = findViewById(R.id.setting_opinion);
        setting_aliyun = findViewById(R.id.setting_aliyun);

        setting_comment_keep = findViewById(R.id.setting_comment_keep);
        setting_prologue_interval = findViewById(R.id.setting_prologue_interval);
        setting_pc = findViewById(R.id.setting_pc);
        setting_prologue_break = findViewById(R.id.setting_prologue_break);
        setting_prologue_restart = findViewById(R.id.setting_prologue_restart);
        setting_prologue_playtype = findViewById(R.id.setting_prologue_playtype);
        setting_keyword_keeptype = findViewById(R.id.setting_keyword_keeptype);

        userDb = new UserDatabase(getApplicationContext());
        userModel = userDb.select();
        if(!userModel.getHeadurl().isEmpty()){
            Uri uri = Uri.parse(userModel.getHeadurl());
            Glide.with(this).load(uri).into(setting_headurl);
        }
        setting_nickname_value.setText(userModel.getNickname());
        setting_comment_keep.setSelected(userModel.getCommentKeep() == 1);
        setting_prologue_interval.setText(String.valueOf(userModel.getPrologueInterval()));
        setting_pc.setText(userModel.getPcIp().isEmpty()?"http://192.168.1.1:5000/data":userModel.getPcIp());
        setting_prologue_break.setSelected(userModel.getPrologueBreak() == 1);
        setting_prologue_restart.setSelected(userModel.getPrologueRestart() == 1);
        setting_prologue_playtype.setSelected(userModel.getProloguePlaytype() == 1);
        setting_keyword_keeptype.setSelected(userModel.getKeywordKeeptype() == 1);
        setting_comment_keep.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(userModel.getCommentKeep() == 1){
                    userModel.setCommentKeep(0);
                    setting_comment_keep.setSelected(false);
                    userDb.updateCommentKeep(0);
                }else{
                    userModel.setCommentKeep(1);
                    setting_comment_keep.setSelected(true);
                    userDb.updateCommentKeep(1);
                }
            }
        });
        //电脑端ip编辑
        setting_pc.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before,int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s.toString())) {
                    userModel.setPcIp(s.toString());
                    userDb.updatePcIp(s.toString());
                }
            }
        });
        //回复文本编辑
        setting_prologue_interval.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before,int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s.toString())) {
                    userModel.setPrologueInterval(Integer.valueOf(s.toString()));
                    userDb.updatePrologueInterval(Integer.valueOf(s.toString()));
                }
            }
        });
        setting_prologue_break.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(userModel.getPrologueBreak() == 1){
                    userModel.setPrologueBreak(0);
                    setting_prologue_break.setSelected(false);
                    userDb.updatePrologueBreak(0);
                }else{
                    userModel.setPrologueBreak(1);
                    setting_prologue_break.setSelected(true);
                    userDb.updatePrologueBreak(1);
                }
            }
        });
        setting_prologue_restart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(userModel.getPrologueRestart() == 1){
                    userModel.setPrologueRestart(0);
                    setting_prologue_restart.setSelected(false);
                    userDb.updatePrologueRestart(0);
                }else{
                    userModel.setPrologueRestart(1);
                    setting_prologue_restart.setSelected(true);
                    userDb.updatePrologueRestart(1);
                }
            }
        });
        setting_prologue_playtype.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(userModel.getProloguePlaytype() == 1){
                    userModel.setProloguePlaytype(0);
                    setting_prologue_playtype.setSelected(false);
                    userDb.updateProloguePlaytype(0);
                }else{
                    userModel.setProloguePlaytype(1);
                    setting_prologue_playtype.setSelected(true);
                    userDb.updateProloguePlaytype(1);
                }
            }
        });
        setting_keyword_keeptype.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(userModel.getKeywordKeeptype() == 1){
                    userModel.setKeywordKeeptype(0);
                    setting_keyword_keeptype.setSelected(false);
                    userDb.updateKeywordKeeptype(0);
                }else{
                    userModel.setKeywordKeeptype(1);
                    setting_keyword_keeptype.setSelected(true);
                    userDb.updateKeywordKeeptype(1);
                }
            }
        });

        setting_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        setting_permission.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getApplicationContext(),PermissionActivity.class));
            }
        });
        setting_opinion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getApplicationContext(),OpinionActivity.class));
            }
        });
        setting_aliyun.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getApplicationContext(),AliyunActivity.class));
            }
        });

        setting_headurl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    //读写(高版本)
                    if(!Environment.isExternalStorageManager()){
                        ToastBottomUtils.Setinfo(getApplicationContext(),"请到设置中授权【读写】权限！");
                        startActivity(new Intent(getApplicationContext(), PermissionActivity.class));
                    }else{
                        getImage();
                    }
                }else{
                    //低版本
                    if(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                            ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                        ToastBottomUtils.Setinfo(getApplicationContext(),"请到设置中授权【读写】权限！");
                        startActivity(new Intent(getApplicationContext(), PermissionActivity.class));
                    }else{
                        getImage();
                    }
                }
            }
        });
        setting_nickname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog_change_nickname();
            }
        });
        setting_pass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog_change_pass();
            }
        });

        setting_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new UpdateChecker(SettingActivity.this,true).checkForUpdates();
            }
        });
        setting_proxy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new UpdateChecker(SettingActivity.this,true).checkForProxy();
            }
        });
        setting_aboutus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getAccount(GetUtil.getAboutus(),GetUtil.getAppInfo(getApplicationContext()).toString(),userModel.getToken(),1);
            }
        });
    }
    public void dialog_about_us(String app_kefu_qrcode,String app_kefu_msg){
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setCancelable(true);
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.dialog_aboutus);
        final ImageView dialog_aboutus_img = window.findViewById(R.id.dialog_aboutus_img);
        final TextView dialog_aboutus_msg = window.findViewById(R.id.dialog_aboutus_msg);
        if(!app_kefu_qrcode.isEmpty()) Glide.with(this).load(app_kefu_qrcode).into(dialog_aboutus_img);
        dialog_aboutus_msg.setText(app_kefu_msg);
    }
    public void dialog_change_nickname(){
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setCancelable(false);
        dialog.setView(new EditText(this));
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.dialog_change_nickname);
        final EditText dialog_change_nickname = window.findViewById(R.id.dialog_change_nickname);
        final TextView dialog_change_nickname_no = window.findViewById(R.id.dialog_change_nickname_no);
        final TextView dialog_change_nickname_ok = window.findViewById(R.id.dialog_change_nickname_ok);
        dialog_change_nickname_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog_change_nickname_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String nickname = dialog_change_nickname.getText().toString();
                newNickname = nickname;
                if(nickname.isEmpty()){
                    ToastUtils.Setinfo(getApplicationContext(),"请输入昵称",2);
                    return;
                }
                try {
                    JSONObject json = new JSONObject();
                    json.put("new_nickname",nickname);
                    getAccount(GetUtil.updateNickname(),json.toString(),userModel.getToken(),3);
                }catch (Exception e){
                    e.printStackTrace();
                }
                dialog.dismiss();
            }
        });
    }
    public void dialog_change_pass(){
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setCancelable(false);
        dialog.setView(new EditText(this));
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.dialog_change_pass);
        final EditText dialog_changepass_old = window.findViewById(R.id.dialog_changepass_old);
        final EditText dialog_changepass_new = window.findViewById(R.id.dialog_changepass_new);
        final EditText dialog_changepass_confirm = window.findViewById(R.id.dialog_changepass_confirm);
        final TextView dialog_changepass_title = window.findViewById(R.id.dialog_changepass_title);
        final TextView dialog_changepass_no = window.findViewById(R.id.dialog_changepass_no);
        final TextView dialog_changepass_ok = window.findViewById(R.id.dialog_changepass_ok);
        dialog_changepass_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog_changepass_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String oldPass = dialog_changepass_old.getText().toString();
                String newPass = dialog_changepass_new.getText().toString();
                String confirmpPass = dialog_changepass_confirm.getText().toString();

                if(oldPass.isEmpty()){
                    dialog_changepass_title.setText("请输入原密码！");
                    return;
                }
                if(newPass.isEmpty()){
                    dialog_changepass_title.setText("请输入新密码！");
                    return;
                }
                if(confirmpPass.isEmpty()){
                    dialog_changepass_title.setText("请输入确认密码！");
                    return;
                }
                if(!confirmpPass.equals(newPass)){
                    dialog_changepass_title.setText("确认密码和新密码不一致！");
                    return;
                }
                try {
                    JSONObject json = new JSONObject();
                    json.put("old_user_password",oldPass);
                    json.put("new_user_password",newPass);
                    getAccount(GetUtil.updatePassword(),json.toString(),userModel.getToken(),2);
                }catch (Exception e){
                    e.printStackTrace();
                }
                dialog.dismiss();
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode){
                case REQUEST_PHOTO_GALLERY:
                    if (data != null) {
                        Glide.with(this).load(data.getData()).into(setting_headurl);
                        userDb.updateUserHeadurl(data.getData().toString());
                    }
                    break;
            }
        }
    }
    public final int REQUEST_PHOTO_GALLERY  =  1;

    //选择图片
    private void getImage() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            startActivityForResult(new Intent(Intent.ACTION_GET_CONTENT).setType("image/*"),REQUEST_PHOTO_GALLERY);
        } else {
            startActivityForResult(new Intent(Intent.ACTION_PICK).setType("image/*"),REQUEST_PHOTO_GALLERY);
        }
    }

    public static int REQUEST_STATUS = 0;
    public static final int RRQUEST_FAILURE = 1;
    public static final int RRQUEST_SUCCESS = 2;

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RRQUEST_FAILURE:
                    ToastBottomUtils.Setinfo(getApplicationContext(),msg.obj.toString());
                    break;
                case RRQUEST_SUCCESS:
                    try {
                        JSONObject json = new JSONObject(msg.obj.toString());
                        if(json.getInt("code") == 1){
                            switch (REQUEST_STATUS){
                                case 1://关于我们
                                    dialog_about_us(json.getJSONObject("data").getString("app_kefu_qrcode"),json.getJSONObject("data").getString("app_kefu_msg"));
                                    break;
                                case 2://更改密码
                                    ToastUtils.Setinfo(getApplicationContext(),json.getString("info"),1);
                                    break;
                                case 3://更改昵称
                                    ToastUtils.Setinfo(getApplicationContext(),json.getString("info"),1);
                                    userDb.updateNickname(newNickname);
                                    setting_nickname_value.setText(newNickname);
                                    break;
                            }
                        }else{
                            ToastBottomUtils.Setinfo(getApplicationContext(),json.getString("info"));
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };
    public void getAccount(String url,String jsonStr,String token,int STATUS){
        OkHttpUtils.sendOkHttpJsonTokenRequest(url, jsonStr,new okhttp3.Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Message message = new Message();
                message.what = RRQUEST_FAILURE;
                message.obj = "【请求异常】请联系管理员";
                handler.sendMessage(message);
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                REQUEST_STATUS = STATUS;
                String responseData = response.body().string();
                Message message = new Message();
                message.what = RRQUEST_SUCCESS;
                message.obj = responseData;
                handler.sendMessage(message);
            }
        },token);
    }
}